package com.hundsun.yr.universal.library.view.hsdialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hundsun.yr.universal.library.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;

/**
 * @Title: HSDialog.java 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @date 2015-12-4 下午3:40:56 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0   
 * 点击取消按钮返回 －1，其他按钮从0开始算
 */

@TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint({ "InflateParams", "ClickableViewAccessibility" }) 
public class HSDialog implements UpdateItem<String>{
    public static enum Style{
        ActionSheet,
        DIALOG
    }
    private final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM
    );
    public static final int HORIZONTAL_BUTTONS_MAXCOUNT = 2;
    public static final String OTHERS = "others";
    public static final String DESTRUCTIVE = "destructive";
    public static final String CANCEL = "cancel";
    public static final String TITLE = "title";
    public static final String MSG = "msg";
    public static final int CANCELPOSITION = -1;//点击取消按钮返回 －1，其他按钮从0开始算

    private String title;
    private String mContent;
    private List<String> mDestructive;
    private List<String> mOthers;
    private String cancel;
    private ArrayList<String> mDatas = new ArrayList<String>();

    private Context context;
    private ViewGroup contentContainer;
    private ViewGroup decorView;//activity的根View
    private ViewGroup rootView;//HSDialog 的 根View
    private ViewGroup linear_header;//窗口headerView

    private Style style = Style.DIALOG;

    private HSDialogOnDismissListener onDismissListener;
    private HSDialogOnItemClickListener onItemClickListener;
    private boolean isDismissing;

    private Animation outAnim;
    private Animation inAnim;
    private int gravity = Gravity.CENTER;
    
    private HolderAdapter<String> mAdapter;
    /**是否有关闭按钮**/
    private boolean hasClose=false;

    /**
     * @param title 标题
     * @param msg 内容
     * @param destructive 高亮按钮数组
     * @param others ActionSheet数组
     * @param context
     * @param style 类型：默认dialog
     * @param onItemClickListener
     */
    public HSDialog(String title, String content, String cancel,String[] destructive, String[] others, Context context, Style style,HSDialogOnItemClickListener onItemClickListener){
    	this.context = context;
        if(style != null)this.style = style;
        this.onItemClickListener = onItemClickListener;

        initData(title, content, cancel, destructive, others);
        initViews();
        init();
        initEvents();
    }
    
    
    /**
     * @param title 标题
     * @param msg 内容
     * @param sure 确定按钮
     * @param context
     * @param onItemClickListener
     */
    public HSDialog(String title, String content, String cancel,String sure, Context context, HSDialogOnItemClickListener onItemClickListener){
    	this.context = context;
        if(style != null)this.style = Style.DIALOG;
        this.onItemClickListener = onItemClickListener;
        String destructive[]={sure};
        initData(title, content, cancel, destructive, null);
        initViews();
        init();
        initEvents();
    }
    
//    /**
//     * ActionSheet
//     * @param title 标题
//     * @param others ActionSheet数组
//     * @param context
//     * @param onItemClickListener
//     */
//    public HSDialog(String title, String[] others,Context context,HSDialogOnItemClickListener onItemClickListener){
//    	this(title,null,"取消",null,others,context,Style.ActionSheet,onItemClickListener);
//    }
//    
    
    
    /**
     * @param title 标题
     * @param msg 内容
     * @param destructive 高亮按钮数组
     * @param others ActionSheet数组
     * @param context
     * @param hasClose 是否带删除按钮
     * @param onItemClickListener
     */
    public HSDialog(String title, String content, String cancel,String[] destructive, String[] others, Context context, boolean hasClose,HSDialogOnItemClickListener onItemClickListener){
    	this.context = context;
        this.style = Style.DIALOG;
        this.onItemClickListener = onItemClickListener;
        this.hasClose=hasClose;
        initData(title, content, cancel, destructive, others);
        initViews();
        init();
        initEvents();
    }

    /**
     * 获取数据
     */
    protected void initData(String title, String content, String cancel, String[] destructive, String[] others) {

        this.title = title;
        this.mContent = content;
        if (destructive != null){
            this.mDestructive = Arrays.asList(destructive);
            this.mDatas.addAll(mDestructive);
        }
        if (others != null){
            this.mOthers = Arrays.asList(others);
            this.mDatas.addAll(mOthers);
        }
        if (!TextUtils.isEmpty(cancel)){
            this.cancel = cancel;
            if(style == Style.DIALOG && mDatas.size() < HORIZONTAL_BUTTONS_MAXCOUNT){
                this.mDatas.add(0,cancel);
            }
        }

    }
    protected void initViews(){
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        decorView = (ViewGroup) ((Activity)context).getWindow().getDecorView().findViewById(android.R.id.content);
        rootView = (ViewGroup) layoutInflater.inflate(R.layout.view_hsdialog_container, decorView, false);
        rootView.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        ));
        contentContainer = (ViewGroup) rootView.findViewById(R.id.content_container);
        int margin_left_right = 0;
        switch (style){
            case ActionSheet:
                params.gravity = Gravity.BOTTOM;
//                margin_left_right = context.getResources().getDimensionPixelSize(R.dimen.margin_actionsheet_left_right);
//                params.setMargins(margin_left_right,0,margin_left_right,margin_left_right);
                contentContainer.setLayoutParams(params);
                gravity = Gravity.BOTTOM;
                initActionSheetViews(layoutInflater);
                break;
            case DIALOG:
                params.gravity = Gravity.CENTER;
                margin_left_right = context.getResources().getDimensionPixelSize(R.dimen.margin_left_right);
                params.setMargins(margin_left_right,0,margin_left_right,0);
                contentContainer.setLayoutParams(params);
                gravity = Gravity.CENTER;
                initDialogViews(layoutInflater);
                break;
        }
    }
    
    /**
     * 加头部
     * @param viewGroup
     */
    protected void initHeaderView(ViewGroup viewGroup){
    	linear_header = (ViewGroup) viewGroup.findViewById(R.id.linear_header);
        //标题和消息
        TextView tv_title = (TextView) viewGroup.findViewById(R.id.tv_title);
        TextView tv_msg = (TextView) viewGroup.findViewById(R.id.tv_msg);
        if(style == Style.DIALOG){
        	ImageView iv_close=(ImageView)viewGroup.findViewById(R.id.iv_close);
        	iv_close.setOnClickListener(new OnClickListener() {
        		
        		@Override
        		public void onClick(View v) {
        			// TODO Auto-generated method stub
        			dismiss();
        		}
        	});
        	if(hasClose){
            	iv_close.setVisibility(View.VISIBLE);
            }else{
            	iv_close.setVisibility(View.GONE);
            }
        }
        if(!TextUtils.isEmpty(title)) {
        	tv_title.setText(title);
        }else{
        	tv_title.setVisibility(View.GONE);
        }
        
        
        if(!TextUtils.isEmpty(mContent)) {
        	if(TextUtils.isEmpty(title)&&hasClose==false){
        		tv_msg.setPadding(0, (int) context.getResources().getDimension(R.dimen.marginBottom_hsdialog_msg), 0, 0);
        	}
        	tv_msg.setText(mContent);
        }else{
        	tv_msg.setVisibility(View.GONE);
        }
    }
    
    
    protected void initListView(){
        ListView mListView = (ListView) contentContainer.findViewById(R.id.lv_dialog);
        mListView.setOverScrollMode(AbsListView.OVER_SCROLL_NEVER);
        //把cancel作为footerView
        if(!TextUtils.isEmpty(cancel) && style == Style.DIALOG){
            View itemView = LayoutInflater.from(context).inflate(R.layout.item_hsdialog_button, null);
            TextView tv_cancle = (TextView) itemView.findViewById(R.id.tv_cancle);
            tv_cancle.setText(cancel);
            tv_cancle.setClickable(true);
            tv_cancle.setTypeface(Typeface.DEFAULT_BOLD);
            tv_cancle.setTextColor(context.getResources().getColor(R.color.textColor_hsdialog_button_cancel));
            tv_cancle.setBackgroundResource(R.drawable.hsdialog_button_bottom_bg);
            tv_cancle.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
            mListView.addFooterView(itemView);
        }
        ViewCreatorHelper<String> creatorHelper=new ViewCreatorHelper<String>(R.layout.item_hsdialog_button, this);
		mAdapter=new HolderAdapter<String>(context,creatorHelper.viewCreator());
		mListView.setAdapter(mAdapter);
		mAdapter.update(mDatas);
//        HSDialogAdapter adapter = new HSDialogAdapter(mDatas,mDestructive);
//        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if(onItemClickListener != null)onItemClickListener.onItemClick(HSDialog.this,position);
                dismiss();
            }
        });
    }
    
    @Override
	public void refreshItem(View view, int position, String data) {
		// TODO Auto-generated method stub
    	TextView tv_cancle = (TextView) view.findViewById(R.id.tv_cancle);
    	tv_cancle.setText(data);
        if (mDestructive!= null && mDestructive.contains(data)){
        	tv_cancle.setTextColor(context.getResources().getColor(R.color.textColor_hsdialog_button_destructive));
        }else{
        	tv_cancle.setTextColor(context.getResources().getColor(R.color.textColor_hsdialog_button_others));
        }
	}
    
    protected void initActionSheetViews(LayoutInflater layoutInflater) {
        ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(R.layout.view_hsdialog_actionsheet,contentContainer);
        initHeaderView(viewGroup);

        initListView();
        TextView tv_cancel = (TextView) contentContainer.findViewById(R.id.tv_cancel);
        if(!TextUtils.isEmpty(cancel)){
        	tv_cancel.setVisibility(View.VISIBLE);
        	tv_cancel.setText(cancel);
        }
        tv_cancel.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
    }
    protected void initDialogViews(LayoutInflater layoutInflater) {

        ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(R.layout.view_hsdialog, contentContainer);
        initHeaderView(viewGroup);

        int position = 0;
        //如果总数据小于等于HORIZONTAL_BUTTONS_MAXCOUNT，则是横向button
        if(mDatas.size()<=HORIZONTAL_BUTTONS_MAXCOUNT){
            ViewStub viewStub = (ViewStub) contentContainer.findViewById(R.id.viewStubHorizontal);
            viewStub.inflate();
            LinearLayout linear_buttons = (LinearLayout) contentContainer.findViewById(R.id.linear_buttons);
            for (int i = 0; i < mDatas.size(); i ++) {
                //如果不是第一个按钮
                if (i != 0){
                    //添加上按钮之间的分割线
                    View divier = new View(context);
                    divier.setBackgroundColor(context.getResources().getColor(R.color.bgColor_divier));
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int)context.getResources().getDimension(R.dimen.size_divier), LinearLayout.LayoutParams.MATCH_PARENT);
                    linear_buttons.addView(divier,params);
                }
                View itemView = LayoutInflater.from(context).inflate(R.layout.item_hsdialog_button, null);
                TextView tv_cancle = (TextView) itemView.findViewById(R.id.tv_cancle);
                tv_cancle.setClickable(true);

                //设置点击效果
                if(mDatas.size() == 1){
                	tv_cancle.setBackgroundResource(R.drawable.hsdialog_button_bottom_bg);
                }
                else if(i == 0){//设置最左边的按钮效果
                	tv_cancle.setBackgroundResource(R.drawable.hsdialog_button_left_bg);
                }
                else if(i == mDatas.size() - 1){//设置最右边的按钮效果
                	tv_cancle.setBackgroundResource(R.drawable.hsdialog_button_right_bg);
                }
                String data = mDatas.get(i);
                tv_cancle.setText(data);

                //取消按钮的样式
                if (data == cancel){
                	tv_cancle.setTypeface(Typeface.DEFAULT_BOLD);
                	tv_cancle.setTextColor(context.getResources().getColor(R.color.textColor_hsdialog_button_cancel));
                	tv_cancle.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
                    position = position - 1;
                }
                //高亮按钮的样式
                else if (mDestructive!= null && mDestructive.contains(data)){
                	tv_cancle.setTextColor(context.getResources().getColor(R.color.textColor_hsdialog_button_destructive));
                }

                tv_cancle.setOnClickListener(new OnTextClickListener(position));
                position++;
                linear_buttons.addView(itemView,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            }
        }
        else{
            ViewStub viewStub = (ViewStub) contentContainer.findViewById(R.id.viewStubVertical);
            viewStub.inflate();
            initListView();
        }
    }
    protected void init() {
        inAnim = getInAnimation();
        outAnim = getOutAnimation();
    }
    protected void initEvents() {
    }
    public HSDialog addExtView(View extView){
    	linear_header.addView(extView);
        return this;
    }
    /**
     * show的时候调用
     *
     * @param view 这个View
     */
    private void onAttached(View view) {
        decorView.addView(view);
        contentContainer.startAnimation(inAnim);
    }
    /**
     * 添加这个View到Activity的根视图
     */
    public void show() {
        if (isShowing()) {
            return;
        }
        onAttached(rootView);
    }
    /**
     * 检测该View是不是已经添加到根视图
     *
     * @return 如果视图已经存在该View返回true
     */
    public boolean isShowing() {
        View view = decorView.findViewById(R.id.outmost_container);
        return view != null;
    }
    public void dismiss() {
        if (isDismissing) {
            return;
        }

        //消失动画
        outAnim.setAnimationListener(new Animation.AnimationListener() {
        	@Override
        	public void onAnimationStart(Animation animation) {
        		
        	}
        	
        	@Override
        	public void onAnimationEnd(Animation animation) {
        		decorView.post(new Runnable() {
        			@Override
        			public void run() {
        				//从activity根视图移除
        				decorView.removeView(rootView);
        				isDismissing = false;
        				if (onDismissListener != null) {
        					onDismissListener.onDismiss(HSDialog.this);
        				}
        			}
        		});
        	}
        	
        	@Override
        	public void onAnimationRepeat(Animation animation) {
        		
        	}
        });
        contentContainer.startAnimation(outAnim);
        isDismissing = true;
    }
    public Animation getInAnimation() {
        int res = HSDialogAnimateUtil.getAnimationResource(this.gravity, true);
        return AnimationUtils.loadAnimation(context, res);
    }

    public Animation getOutAnimation() {
        int res = HSDialogAnimateUtil.getAnimationResource(this.gravity, false);
        return AnimationUtils.loadAnimation(context, res);
    }

    
    /**
     * dismiss监听
     * @param onDismissListener
     * @return
     */
    public HSDialog setOnDismissListener(HSDialogOnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
        return this;
    }
    
    
    /**
     * Item 监听
     * @param onItemClickListener
     * @return
     */
    public HSDialog setOnItemClickListener(HSDialogOnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
        return this;
    }

    class OnTextClickListener implements View.OnClickListener{

        private int position;
        public OnTextClickListener(int position){
            this.position = position;
        }
        @Override
        public void onClick(View view) {
            if(onItemClickListener != null)onItemClickListener.onItemClick(HSDialog.this,position);
            dismiss();
        }
    }

    /**
     * 主要用于拓展View的时候有输入框，键盘弹出则设置MarginBottom往上顶，避免输入法挡住界面
     */
    public void setMarginBottom(int marginBottom){
        int margin_left_right = context.getResources().getDimensionPixelSize(R.dimen.margin_left_right);
        params.setMargins(margin_left_right,0,margin_left_right,marginBottom);
        contentContainer.setLayoutParams(params);
    }
    
    /**
     * 模拟dialog的setCancelable
     * @param isCancelable
     * @return
     */
    public HSDialog setCancelable(boolean isCancelable) {
        View view = rootView.findViewById(R.id.outmost_container);

        if (isCancelable) {
            view.setOnTouchListener(onCancelableTouchListener);
        }
        else{
            view.setOnTouchListener(null);
        }
        return this;
    }
    /**
     * 
     * 按下空白处弹窗消失
     * 
     */
    private final View.OnTouchListener onCancelableTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                dismiss();
            }
            return false;
        }
    };
    
    
    /**
     * @Title: OnDismissListener.java 
     * @Description: TODO(用一句话描述该文件做什么) 
     * @date 2015-9-7 下午3:41:49 
     * @author:hejun.shen
     * @email:shenhj15971@hundsun.com 
     * @replace author:
     * @replace date:
     * @version V1.0   
     */
    public interface HSDialogOnDismissListener {
    	public void onDismiss(Object o);
    }


    

    /**
     * @Title: OnItemClickListener.java 
     * @Description: TODO(用一句话描述该文件做什么) 
     * @date 2015-9-7 下午3:42:00 
     * @author:hejun.shen
     * @email:shenhj15971@hundsun.com 
     * @replace author:
     * @replace date:
     * @version V1.0   
     */
    public interface HSDialogOnItemClickListener {
    	public void onItemClick(Object o,int position);
    }


}
